<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <a-row >
          <div :class="advanced ? null: 'fold'">
            <a-col :md="6" :sm="24" >
              <a-form-item
                label="服务名称"
                :labelCol="{span: 6}"
                :wrapperCol="{span: 17, offset: 1}">
                <a-input v-model="queryParams.name"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" >
              <a-form-item
                label="服务SN"
                :labelCol="{span: 6}"
                :wrapperCol="{span: 17, offset: 1}">
                <a-input v-model="queryParams.sn"/>
              </a-form-item>
            </a-col>
          </div>
          <span style="float: right; margin-top: 3px;">
            <a-button type="primary" @click="search">查询</a-button>
            <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          </span>
        </a-row>
      </a-form>
    </div>
    <div>
      <div class="operator">
        <a-button type="primary" ghost @click="add" v-hasPermission="'service:add'">新增</a-button>
        <a-button @click="batchDelete" v-hasPermission="'service:delete'">删除</a-button>
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :rowKey="record => record.id"
               :scroll="{ x: 900 }"
               @change="handleTableChange">
        <template slot="pic" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <img slot="reference" :src="text" :alt="text" style="height: 150px;width: 150px">
            </template>
            <img :src="text" style="height: 40px;width: 40px" />
          </a-popover>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon v-hasPermission="'service:update'" type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="edit(record)" title="修改服务"></a-icon>
          &nbsp;
          <a-badge v-hasNoPermission="'service:update'" status="warning" text="无权限"></a-badge>
        </template>
      </a-table>
    </div>
    <!-- 新增服务 -->
    <service-add
      @close="handleServiceAddClose"
      @success="handleServiceAddSuccess"
      :serviceAddVisiable="serviceAddVisiable">
    </service-add>
    <!-- 修改服务 -->
    <service-edit
      ref="serviceEdit"
      @close="handleServiceEditClose"
      @success="handleServiceEditSuccess"
      :serviceEditVisiable="serviceEditVisiable">
    </service-edit>
  </a-card>
</template>

<script>
import ServiceAdd from './ServiceAdd'
import ServiceEdit from './ServiceEdit'
import defaultPagination from '../../../utils/common'

export default {
  name: 'Service',
  components: { ServiceAdd, ServiceEdit },
  data () {
    return {
      advanced: false,
      serviceAddVisiable: false,
      serviceEditVisiable: false,
      queryParams: {},
      filteredInfo: null,
      selectedRowKeys: [],
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      loading: false,
      pagination: defaultPagination
    }
  },
  computed: {
    columns () {
      // eslint-disable-next-line no-unused-vars
      let { sortedInfo, filteredInfo } = this
      sortedInfo = sortedInfo || {}
      filteredInfo = filteredInfo || {}
      return [{
        title: '封面',
        dataIndex: 'cover',
        scopedSlots: { customRender: 'pic' },
        width: 50,
        key: 'cover'
      }, {
        title: '服务名称',
        dataIndex: 'name',
        key: 'name'
      }, {
        title: '服务SN',
        dataIndex: 'sn',
        key: 'sn'
      }, {
        title: '分类名称',
        dataIndex: 'categoryName',
        key: 'categoryName'
      }, {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        customRender: (text, row, index) => {
          switch (text) {
            case 'ENABLE':
              return <a-tag color="cyan">开启</a-tag>
            case 'DISABLE':
              return <a-tag color="red">关闭</a-tag>
            default:
              return <a-tag color="yellow">未知</a-tag>
          }
        },
        filters: [
          { text: '开启', value: 'ENABLE' },
          { text: '关闭', value: 'DISABLE' }
        ],
        filterMultiple: false,
        filteredValue: filteredInfo.status || null,
        onFilter: (value, record) => record.status.includes(value)
      }, {
        title: '是否免费',
        dataIndex: 'isFree',
        key: 'isFree',
        customRender: (text, row, index) => {
          switch (text) {
            case 'true':
              return <a-tag color="cyan">是</a-tag>
            case 'false':
              return <a-tag color="red">否</a-tag>
            default:
              return <a-tag color="yellow">未知</a-tag>
          }
        },
        filters: [
          { text: '是', value: 'true' },
          { text: '否', value: 'false' }
        ],
        filterMultiple: false,
        filteredValue: filteredInfo.isFree || null,
        onFilter: (value, record) => record.isFree.includes(value)
      }, {
        title: '服务描述',
        dataIndex: 'desc',
        key: 'desc'
      }, {
        title: '操作',
        dataIndex: 'operation',
        scopedSlots: { customRender: 'operation' }
      }]
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    add () {
      this.serviceAddVisiable = true
    },
    handleServiceAddClose () {
      this.serviceAddVisiable = false
    },
    handleServiceAddSuccess () {
      this.serviceAddVisiable = false
      this.$message.success('新增服务成功')
      this.search()
    },
    edit (record) {
      this.$refs.serviceEdit.setFormValues(record)
      this.serviceEditVisiable = true
    },
    handleServiceEditClose () {
      this.serviceEditVisiable = false
    },
    handleServiceEditSuccess () {
      this.serviceEditVisiable = false
      this.$message.success('修改服务成功')
      this.search()
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let serviceIds = that.selectedRowKeys.join(',')
          that.$delete('serviceInfo/' + serviceIds).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.search()
          }).catch(() => {
            this.loading = false
            that.$message.error('删除失败')
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    search () {
      let {sortedInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.restPagination()
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      this.restPagination()
      // 重置列过滤器规则
      this.filteredInfo = null
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    restPagination () {
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
    },
    handleTableChange (pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter

      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    fetch (params = {}) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      this.$get('serviceInfo', {
        ...params
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        // 数据加载完毕，关闭loading
        this.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
  @import "../../../../static/less/Common";
</style>
